package dao;

import java.util.List;

import pojo.Topic;
import utils.PreHandle;

public class TopicDao {

	public static List<Topic> doTopicSearch() {
		String sql = "select * from topic";
		return PreHandle.query(sql, Topic.class);
	}

	public static Boolean deleteTopic(Integer tid) {
		String sql = "delete from topic where tid=?";
		boolean isOk = false;
		try {
			isOk = PreHandle.excuteUpdate(sql, tid) == 1;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isOk;
	}

	public static Topic doSearchById(Integer tid) {

		String sql = "select * from topic where tid=?";

		List<Topic> list = PreHandle.query(sql, Topic.class, tid);

		return list.size() == 0 ? null : list.get(0);

	}

	public static Boolean updateTopic(Topic topic) {
		Topic topics = null;
		try {
			topics = doSearchByName(topic.getTname());
		} catch (NullPointerException NPE) {
			NPE.printStackTrace();
		}

		if (topics != null && topics.getTid() != topic.getTid()) {
			return false;
		}

		String sql = "update topic set tname=? where tid=?";
		boolean isOk = false;
		try {
			isOk = PreHandle.excuteUpdate(sql, topic) == 1;
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return isOk;

	}

	public static Topic doSearchByName(String tname) {
		List<Topic> list = null;
		String sql = "select * from topic where tname=?";
		try {
			list = PreHandle.query(sql, Topic.class, tname);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list.size() == 0 ? null : list.get(0);

	}

	public static Boolean addTopic(Topic topic) {

		int i = 0;

		String sql = "insert into topic (tname) values(?)";

		Topic toc = doSearchByName(topic.getTname());

		System.out.println(toc != null);

		if (toc != null) {
			return false;
		}

		try {
			i = PreHandle.excuteUpdate(sql, topic);
		} catch (IllegalArgumentException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return i == 1;

	}
}